//
//  BIZOfflineConsultQuestionVC.m
//  biz
//
//  Created by zhangfuwei on 2017/4/17.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZOfflineConsultQuestionVC.h"
#import "BIZConsultorListViewController.h"

// view
#import "BIZOfflineCalendarView.h"
#import "BIZOfflineConsultorView.h"

// model
#import "BIZConsultorListDataModel.h"

typedef enum : NSInteger {
    BIZOfflineConsultQuestionVCSetTypeNone = 0,
    BIZOfflineConsultQuestionVCSetTypeStartTime,
    BIZOfflineConsultQuestionVCSetTypeEndTime
} BIZOfflineConsultQuestionVCSetType;

/*默认占位字符*/
static NSString *const kDefaultPlaceHolder = @"请输入您的线下咨询要求,您还可以输入300字......";

@interface BIZOfflineConsultQuestionVC ()<UITextViewDelegate>

//  控件
/** scrollView */
@property (nonatomic, strong) UIScrollView *scrollView;
/** 顶部视图 */
@property (nonatomic, strong) UIView *topSubView;
/** 底部视图 */
@property (nonatomic, strong) UIView *bottomSubView;
/** 输入问题的textView */
@property (nonatomic, strong) UITextView *inputTextView;
/** 输入问题的textView */
@property (nonatomic, strong) UITextField *inputTextField;
/** 分割线 */
@property (nonatomic, strong)   UIView  *splitLine;
/** 选择咨询师按钮 */
@property (nonatomic, strong) UIButton *chooseButton;

/** 日期选择 */
@property (nonatomic, strong) BIZOfflineCalendarView *calendarView;

/** 咨询师详情视图 */
@property (nonatomic, strong) BIZOfflineConsultorView *offlineConsultorView;

/** coverView */
@property (nonatomic, strong)  UIView *coverView;

/** pickerView */
@property (nonatomic, strong) UIDatePicker *datePicker;

/** setButton */
@property (nonatomic, strong) UIButton *setButton;

/** cancelButton */
@property (nonatomic, strong) UIButton *cancelButton;

//  变量
/** isSetStartTime */
@property (nonatomic, assign) BOOL isSetStartTime;

/** set类型 */
@property (nonatomic, assign) BIZOfflineConsultQuestionVCSetType setType;

/** 时间戳 */
@property (nonatomic, assign) NSInteger timeStamp;

@end

@implementation BIZOfflineConsultQuestionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupConfig];
    // 时间戳
    [self requestTimestamp];
    
    [self loadUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadDynamicBottomView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 视图初始化

- (void)setupConfig {
    
    self.timeStamp = 0;
    self.setType = BIZOfflineConsultQuestionVCSetTypeNone;
    
    self.view.backgroundColor = HEXCOLOR(0xf9f9f9);
    
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 62, 15)];
    titleLab.textColor = [UIColor whiteColor];
    titleLab.font = CHINESE_SYSTEM(16);
    titleLab.text = @"线下咨询";
    self.navigationItem.titleView = titleLab;
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 14)];
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = CHINESE_SYSTEM(14);
    [btn addTarget:self action:@selector(offlineConsultSubmitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
}


- (void)loadUI {
    
//    CGFloat kMargin = 10;
    CGFloat kViewMargin = 15;
    _scrollView = [[UIScrollView  alloc] initWithFrame:CGRectMake(0, 0, self.view.size.width, self.view.size.height-BIZNavgationBarH)];
//    _scrollView.backgroundColor = HEXCOLOR(0xf9f9f9f);
    [self.view addSubview:_scrollView];
    
    //  顶部,底部视图
    _topSubView = [[UIView alloc] init];
    _topSubView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_topSubView];
    [self.view addSubview:_bottomSubView];

    _bottomSubView = [[UIView alloc] init];
    _bottomSubView.backgroundColor = [UIColor whiteColor];

    // 添加子控件子控件
    _inputTextView = [[UITextView alloc] init];
    _inputTextView.delegate = self;
    [_inputTextView setText:kDefaultPlaceHolder];
    [_inputTextView setTextColor:HEXCOLOR(0xcccccc)];
    [_inputTextView setFont:CHINESE_SYSTEM(15)];
    _splitLine = [[UIView alloc] init];
    _splitLine.backgroundColor = HEXCOLOR(0xeeedee);
    
    
    _calendarView = [[BIZOfflineCalendarView alloc] init];
    _calendarView.block = [self returnDropdownBlock];
    
    
    _chooseButton = [[UIButton alloc] init];
    _chooseButton.layer.cornerRadius = 23;
    _chooseButton.clipsToBounds = YES;
//    [_chooseButton setTitle:@"选择咨询师" forState:UIControlStateNormal];
//    [_chooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [_chooseButton setBackgroundColor:HEXCOLOR(0xfb6b2f)];
    [_chooseButton setBackgroundImage:[UIImage imageNamed:@"offline_chooseButtonBg"] forState:UIControlStateNormal];
    [_chooseButton addTarget:self action:@selector(chooseConsultorBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _offlineConsultorView = [[BIZOfflineConsultorView alloc] init];
    _offlineConsultorView.hidden = YES;
    _offlineConsultorView.rechooseBlock = [self returnRechooseBlock];
    
    
    [_topSubView addSubview:_inputTextView];
    [_topSubView addSubview:_splitLine];
    [_topSubView addSubview:_calendarView];
    [_topSubView addSubview:_chooseButton];
    [_bottomSubView addSubview:_offlineConsultorView];
    [self.view addSubview:_topSubView];
    [self.view addSubview:_bottomSubView];

    //  布局约束
    [_topSubView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view).offset(kViewMargin);
        make.right.equalTo(self.view).offset(-1*kViewMargin);
        make.height.equalTo(@415);
    }];
    
    [_bottomSubView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_topSubView.mas_bottom).offset(kViewMargin);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@100);
        // MARK:TO DO
//        make.bottom.equalTo(_scrollView);
    }];
    
    [_inputTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(_topSubView);
        make.height.equalTo(@224);
    }];
    
    [_splitLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_topSubView).offset(kViewMargin);
        make.right.equalTo(_topSubView).offset(-1*kViewMargin);
        make.top.equalTo(_inputTextView.mas_bottom);
        make.height.equalTo(@0.5);
    }];

    
    [_calendarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_splitLine.mas_bottom);
        make.left.right.equalTo(_topSubView);
    }];
    
    [_chooseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_calendarView.mas_bottom).offset(7);
        make.left.equalTo(_topSubView).offset(15);
        make.right.equalTo(_topSubView).offset(-1*15);
        make.height.equalTo(@45);
    }];
    
    [_offlineConsultorView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.top.equalTo(_bottomSubView);
        make.edges.equalTo(_bottomSubView);
    }];

}

- (void)loadDynamicBottomView {
    
    if (self.dataM == nil) {
        [_topSubView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@415);
        }];
        [_bottomSubView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@0);
        }];

        _chooseButton.hidden = NO;
        _offlineConsultorView.hidden = YES;
        
    }else {
        
        [_topSubView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@342);
        }];
        [_bottomSubView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@100);
        }];

        _chooseButton.hidden = YES;
        _offlineConsultorView.hidden = NO;
        _offlineConsultorView.dataModel = self.dataM;

    }
}
#pragma mark -- 网络请求

- (void)submitOfflineConsultQuestion {

    NSDictionary *parm = @{@"content":_inputTextView.text,@"cuserId":_dataM.uuid,@"startTime":_calendarView.startTime,@"endTime":_calendarView.endTime};
    
    [RequestTool POST:kOfflienConsultQuestionSubmitURL
           parameters:parm
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"线下咨询问题提交--%@",responseObject);
                  [MBProgressHUD showSuccessMessage:@"业务数据请求成功"];
                  NSString *code = responseObject[@"code"];
                  if (code.intValue == 1) {
                      
                      [MBProgressHUD showSuccessMessage:@"提交成功"];
                      [self.navigationController popViewControllerAnimated:YES];
                      
                  }else{
                      [MBProgressHUD showErrorMessage:@"提交失败"];
                  }

                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  DeLog(@"error ---%@",error);
                  
              }
     ];

}

- (void)requestTimestamp {
    
        [RequestTool POST:kOfflineConsultReturnTimestampURL
           parameters:nil
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"时间戳--%@",responseObject);
        
                  NSString *code = responseObject[@"code"];
                  if (code.intValue == 1) {
                      NSString *timeStampStr = responseObject[@"data"];
                      _timeStamp = timeStampStr.integerValue;
                      
                  }else{
                      [MBProgressHUD showErrorMessage:@"服务器时间获取失败"];
                  }
                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  DeLog(@"error ---%@",error);
                  
              }
     ];
    
}

#pragma mark -- 数据源,代理
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    if ([textView.text isEqualToString:kDefaultPlaceHolder]) {
        
        _inputTextView.text = @"";
        [_inputTextView setTextColor:HEXCOLOR(0x000000)];

    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    
    NSString *text = [textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    if (text.length == 0) {
        _inputTextView.text = kDefaultPlaceHolder;
        [_inputTextView setTextColor:HEXCOLOR(0xcccccc)];
    }

    return YES;
}


#pragma mark -- 私有方法
- (void)offlineConsultSubmitBtnClick:(UIButton* )btn {
    if (!_dataM.uuid) {
        [MBProgressHUD showErrorMessage:@"请选择咨询师"];
        return;
    }
    
    if (!_calendarView.startTime || !_calendarView.endTime) {
        [MBProgressHUD showErrorMessage:@"请选择服务起止时间"];
        return;
    }
    
    if (!_inputTextView.text.length) {
        [MBProgressHUD showErrorMessage:@"请输入要咨询的问题"];
        return;
    }
    
    [self submitOfflineConsultQuestion];
}


- (void)chooseConsultorBtnClick:(UIButton *)btn {
    BIZConsultorListViewController *listVC = [[BIZConsultorListViewController alloc] initWithType:BIZConsultorListViewControllerTypeFromOffline];
    
    [self.navigationController pushViewController:listVC animated:YES];
    
}


- (BIZOfflineConsultorViewRechooseBlock)returnRechooseBlock {
    BIZOfflineConsultorViewRechooseBlock block = nil;
    
    __weak BIZOfflineConsultQuestionVC *weakSelf = self;
    block = ^ {
        BIZConsultorListViewController *listVC = [[BIZConsultorListViewController alloc] initWithType:BIZConsultorListViewControllerTypeFromOffline];
        
        [weakSelf.navigationController pushViewController:listVC animated:YES];

    };
    
    return block;
}

- (BIZOfflineCalendarViewDropdownBlock)returnDropdownBlock {
    
    BIZOfflineCalendarViewDropdownBlock block = nil;
    __weak BIZOfflineConsultQuestionVC *weakSelf = self;
    block = ^ (NSInteger tag){
        if (tag && !_calendarView.startTime) { // 设置服务结束时间
            [MBProgressHUD showTipMessageInView:@"请先设置服务开始时间"];
            return ;
        }
        
        _setType = !tag ? BIZOfflineConsultQuestionVCSetTypeStartTime : BIZOfflineConsultQuestionVCSetTypeEndTime;
        [weakSelf.view endEditing:YES];
        
        UIView *coverView = [[UIView alloc] initWithFrame:self.view.bounds];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeCoverViewFromSuperview)];
        [coverView addGestureRecognizer:tap];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.alpha = 0.5;
        
        
        UIDatePicker *datePicker = [[ UIDatePicker alloc] init];
        datePicker.datePickerMode = UIDatePickerModeDate;

        NSDateFormatter *dateFormatter = [NSDateFormatter sharedDateFormatter];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
       
        NSDate *minDate;
        NSDate *maxDate;
        // 当设置开始时间时(tag = 0),以服务器时间为准; 设置服务结束时间时,以开始时间为准.
        minDate = !tag ? [NSDate dateWithTimeIntervalSince1970:_timeStamp/1000.00] : [dateFormatter dateFromString:_calendarView.startTime];
        maxDate = !tag ? [dateFormatter dateFromString:_calendarView.endTime]:nil;
        
        datePicker.minimumDate = minDate;
        datePicker.maximumDate = maxDate;
        datePicker.backgroundColor = [UIColor whiteColor];

        
        UIButton *setButton = [UIButton buttonWithType:UIButtonTypeCustom];
        setButton.backgroundColor = [UIColor whiteColor];
        [setButton setTitle:@"设置" forState:UIControlStateNormal];
        [setButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [setButton addTarget:weakSelf action:@selector(setButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.backgroundColor = [UIColor whiteColor];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [cancelBtn addTarget:weakSelf action:@selector(removeCoverViewFromSuperview) forControlEvents:UIControlEventTouchUpInside];

        _coverView = coverView;
        _datePicker = datePicker;
        _setButton = setButton;
        _cancelButton = cancelBtn;
        
        
        [weakSelf.view addSubview:_coverView];
        [weakSelf.view insertSubview:_datePicker aboveSubview:_coverView];
        [weakSelf.view insertSubview:_setButton aboveSubview:_coverView];
        [weakSelf.view insertSubview:_cancelButton aboveSubview:_coverView];
        
        [_datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(weakSelf.view);
        }];
        [_setButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_datePicker);
            make.top.equalTo(_datePicker.mas_bottom);
            make.height.equalTo(@30);
            make.width.equalTo(@(_datePicker.size.width/2));
        }];
        [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_setButton.mas_right);
            make.top.width.height.equalTo(_setButton);
        }];
    };

    
    return block;
}

- (void)setButtonClick:(UIButton *)btn {
    DeLog(@"%@",_datePicker.date);
    NSDateFormatter *dateFormatter = [NSDateFormatter sharedDateFormatter];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *dateStr = [dateFormatter stringFromDate:_datePicker.date];
    [self removeCoverViewFromSuperview];
    if (!dateStr) return;
    
    
    if (_setType == BIZOfflineConsultQuestionVCSetTypeStartTime) {
        
        _calendarView.startTime = dateStr;
    }else if (_setType == BIZOfflineConsultQuestionVCSetTypeEndTime) {
        
        _calendarView.endTime = dateStr;
    }
}

- (void)removeCoverViewFromSuperview {
    [UIView animateWithDuration:2
                          delay:0
         usingSpringWithDamping:0.5
          initialSpringVelocity:5
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         [self.coverView removeFromSuperview];
                         [self.datePicker removeFromSuperview];
                         [self.setButton removeFromSuperview];
                         [self.cancelButton removeFromSuperview];
                         self.setButton = nil;
                         self.cancelButton = nil;
                         self.coverView = nil;
                         self.datePicker = nil;
                     }
                     completion:nil];
}



@end
